'use strict';

const Controller = require('egg').Controller;

class ShortConnection extends Controller {

  /**
   * 获取QQ用户信息
   */
  async qqInfo() {
    const { ctx } = this;
    ctx.validate({
      accessToken: {
        type: 'string',
      },
    }, this.ctx.query);
    const { accessToken } = this.ctx.query;
    // 获取 openid
    const { OpenIDUrl, userInfoUrl, appid } = this.app.config.OAuth.qq;
    const responce = await ctx.$wGet(OpenIDUrl, {
      access_token: accessToken,
    }, {
      dataType: 'text',
    });
    const jsonData = responce.data.substring(10, responce.data.length - 4);
    const openid = JSON.parse(jsonData).openid;
    const userInfoResponce = await ctx.$wGet(userInfoUrl, {
      access_token: accessToken,
      openid,
      appid,
    });
    // 记录用户登录的数据
    const usreData = {
      name: userInfoResponce.data.nickname,
      icon: userInfoResponce.data.figureurl_2.replace("http://","https://"),
      userId: openid,
      type: 0,
    };
    this.ctx.session.OAuthUserInfo = usreData;
    // 获取用户信息
    this.ctx.sendSuccess(usreData);
  }

  /**
   * session登录
   */
  async sessionLogin() {
    const { OAuthUserInfo } = this.ctx.session;
    return this.ctx.sendSuccess(OAuthUserInfo);
  }

  /**
   * 退出登录
   */
  async logout() {
    this.ctx.session.OAuthUserInfo = null;
    this.ctx.sendSuccess();
  }
}

module.exports = ShortConnection;
